﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://www.codeplex.com/EmlenMud
using System;
using BrainTechLLC.ThreadSafeObjects;
using LinFu.AOP.Interfaces;

namespace BrainTechLLC
{
	public class CountCallsWrapper : AroundMethodBase, IAroundInvoke
	{
		/// <summary>
		/// Reads the count of calls for a class and method name (only functional if the method is marked with the CountCalls attribute)
		/// </summary>
		public static ThreadSafeCounter GetCounter<T>(string methodName)
		{
			ThreadSafeCounter result;

			if (Lookups.CounterLookup.TryGetValue(typeof(T).DotMethodName(methodName), out result))
				return result;

			return null;
		}

		protected override void Execute(IInvocationContext context, CutpointType when, object returnValue)
		{
			object thisObject = context.Target;
			Type t = thisObject.GetType();
			CountCallsAttribute[] attrs = context.TargetMethod.ReadAttribute<CountCallsAttribute>();

			if (attrs != null && attrs.Length > 0)
			{
				string key = t.DotMethodName(context.TargetMethod.Name);
				ThreadSafeCounter counter = Lookups.CounterLookup.Get(key);
				attrs.ForEachAttribute(attr => counter += attr.IncrementAmount);				
			}
		}
	}
}

